import sys
import pathlib
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
import os
import tempfile
import pytest

from app import create_app, db


@pytest.fixture(scope="session")
def app():
	# Use a temp sqlite database for tests
	db_fd, db_path = tempfile.mkstemp(prefix="rbac_test_", suffix=".sqlite")
	os.close(db_fd)
	os.environ["DB_TYPE"] = "sqlite"
	os.environ["SQLITE_PATH"] = db_path
	os.environ["FLASK_ENV"] = "development"

	app = create_app("development")
	with app.app_context():
		db.create_all()
		yield app
		# Teardown
		db.session.remove()
		db.drop_all()
		try:
			os.remove(db_path)
		except OSError:
			pass


@pytest.fixture()
def client(app):
	return app.test_client()


@pytest.fixture()
def tokens(client):
	# Register user and return access/refresh tokens
	resp = client.post("/auth/register", json={
		"username": "tester",
		"email": "tester@example.com",
		"password": "Test@123456"
	})
	assert resp.status_code == 200
	data = resp.get_json()
	return data["data"]


